<?php

namespace app\api\services;

use app\api\cache\KeysUtil;
use app\api\cache\RedisCache;
use app\common\libs\Singleton;
use app\common\models\Community\CommunityTransferCountLog;
use app\common\models\Member\MemberClickLog;
use app\common\models\Member\MemberNum;
use app\common\models\Sys\ShopConfig;
use app\Request;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;
use think\facade\Log;

class MemberInfoService
{
    use Singleton;

    /**
     * @throws ModelNotFoundException
     * @throws DataNotFoundException
     * @throws DbException
     */
    public function memberClick($userId,$device,$phone): bool
    {
        //$device = request()->header('romName');
        $where = [
            ['user_id','=',$userId],
            ['create_at','>=',date('Y-m-d')]
        ];
        $ret = MemberClickLog::getInstance()->where($where)->find();
        if(!empty($ret)){
            $ret->update_at = date('Y-m-d H:i:s');
            $ret->save();
        }else{
            $data = [
                'user_id' => $userId,
                'device' => $device,
                'phone' => $phone,
                'update_at' =>  date('Y-m-d H:i:s'),
            ];
            MemberClickLog::getInstance()->insert($data);
        }
        return true;
    }

    /**
     * @throws ModelNotFoundException
     * @throws DataNotFoundException
     * @throws DbException
     */
    public function memberNum($userId): array
    {
        $memberNum = MemberNum::getInstance()->where('user_id',$userId)->find();
        if(empty($memberNum)){
            $insertData = [
                'user_id' => $userId
            ];
            $ret = MemberNum::getInstance()->insert($insertData);
            if(!$ret){
                return [];
            }
            $memberNum = MemberNum::getInstance()->where('user_id',$userId)->find();
        }
        return !empty($memberNum) ? $memberNum->toArray() : [];
    }

    public function withdrawConfig($type){
        $ret = RedisCache::hGetAll(KeysUtil::getSystemConfigKey('withdraw'));
        if (empty($ret)) {
            $config = ShopConfig::getInstance()->where('type', 'withdraw')->select();
            foreach ($config as $v) {
                RedisCache::hSet(KeysUtil::getSystemConfigKey('withdraw'), $v['configKey'], $v['configValue']);
                $ret[$v['configKey']] = $v['configValue'];
            }
        }
        foreach ($ret as $k => $v) {
            $ret[$k] = json_decode($v, true);
        }
        return $ret[$type] ?? [];
    }

    /**
     * @throws ModelNotFoundException
     * @throws DataNotFoundException
     * @throws DbException
     */
    public function addCommunityTransferCount($userId, $count, $status, $orderNo = '', $msg = ''): bool
    {
        $finance = MemberInfoService::getInstance()->memberNum($userId);
        $thisAmount = $finance['transferCount'];

        if ($status == 1) {
            $alterAmount = bcadd($thisAmount, $count, 2);
        } else {
            $alterAmount = bcsub($thisAmount, $count, 2);
        }

        $data = [
            'user_id'      => $finance['userId'],
            'status'       => $status,
            'remark'       => $msg,
            'this_amount'  => $thisAmount,
            'alter_amount' => $alterAmount,
            'amount'       => $count,
            'order_no'     => $orderNo,
        ];
        CommunityTransferCountLog::getInstance()->insert($data);
        if ($status == 1) {
            MemberNum::getInstance()->where('user_id',$userId)->inc('transfer_count',$count)->update();
        } else {
            MemberNum::getInstance()->where('user_id',$userId)->dec('transfer_count',$count)->update();
        }
        MemberNum::getInstance()->where('user_id',$userId)->update(['transfer_update_at' => date('Y-m-d H:i:s')]);
        return true;
    }


}